require "sunspot_kaminari_support/version"

module SunspotKaminariSupport
  # Returns:
  #   => Current page number
  #
  def current_page
    query.page
  end

  # Returns:
  #   => Total number of pages
  #
  def total_pages
    (total.to_f / query.per_page).ceil
  end

  # Returns:
  #    => Number of records displayed per page
  #
  def limit_value
    query.per_page || Kaminari.config.default_per_page
  end


  # Returns:
  #    => true if result is blank
  #
  def empty?
    total == 0
  end

  # Returns:
  #    => true if there are any results
  def any?
    total > 0
  end

  # Changes page query param
  def page(new_page)
    query.paginate(new_page, nil)
    self
  end

  # Returns:
  #   => true if current_page is last or bigger
  def last_page?
    current_page >= total_pages
  end

  # Returns:
  #   => true if current_page equals 1
  def first_page?
    current_page == 1
  end

  # Methods for page_entries_info helper
  #

  # Returns:
  #   => Total number of records before current page
  #
  def offset_value
    query.per_page * (query.page - 1)
  end


  # Returns:
  #   => Total number of records found
  #
  def total_count
    total
  end
end

# Add methods to sunspot results
if defined?(Sunspot)
  Sunspot::Search::AbstractSearch.send(:include, SunspotKaminariSupport)
else
  puts "[SunspotKaminariSupport] WARNING: Sunspot not found"
end

# Add methods to stub provided by sunspot_rails
if defined?(Sunspot::Rails::StubSessionProxy::Search)
  Sunspot::Rails::StubSessionProxy::Search.send(:include, SunspotKaminariSupport)
end
